package cn.nexttec.noteplayer.ui.settings

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import cn.nexttec.noteplayer.common.AESUtil
import cn.nexttec.noteplayer.common.PERMISSION
import cn.nexttec.noteplayer.common.PermissionHelper
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.VOSK
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.databinding.FragmentSettingsBinding
import cn.nexttec.noteplayer.events.CameraPermissionEvent
import cn.nexttec.noteplayer.ui.widget.PopupDialog
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import javax.inject.Inject

@AndroidEntryPoint
class PlayerSettingFragment : Fragment() {
    private var suppressToggleCallback = false
    private val handler = Handler(Looper.getMainLooper())
    @Inject
    lateinit var preference: Preference
    private var _binding: FragmentSettingsBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingsBinding.inflate(inflater, container, false)
        if (EventBus.getDefault().isRegistered(this).not()) {
            EventBus.getDefault().register(this)
        }
        initSwitches()
        setupResetButton()
        return binding.root
    }

    private fun initSwitches() {
        // 默认影院模式
        binding.swMovieMode.isChecked = preference.isMovieMode
        binding.swMovieMode.setOnCheckedChangeListener { _, isChecked ->
            preference.isMovieMode = isChecked
        }

        // 开屏动画跳过
        binding.swAnimation.isChecked = preference.isSkipAnimation
        binding.swAnimation.setOnCheckedChangeListener { _, isChecked ->
            preference.isSkipAnimation = isChecked
        }

        binding.swAutoReplay.isChecked = preference.isAutoPlayNextVideo
        binding.swAutoReplay.setOnCheckedChangeListener { buttonView, isChecked ->
            preference.isAutoPlayNextVideo = isChecked
        }

        // 息屏播放
        binding.swAudio.isChecked = preference.enableAudioMode
        binding.swAudio.setOnCheckedChangeListener { _, isChecked ->
            preference.enableAudioMode = isChecked
        }

        // 播放不关闭其他声源
        binding.swBlockMp3.isChecked = preference.keepOtherAudio
        binding.swBlockMp3.setOnCheckedChangeListener { _, isChecked ->
            preference.keepOtherAudio = isChecked
        }

        // 启用隐私保护（需要设置密码）
        binding.swEnaPrivate.isChecked = preference.enablePrivate
        binding.swEnaPrivate.setOnCheckedChangeListener { _, isChecked ->
            if (suppressToggleCallback) {
                suppressToggleCallback = false
                return@setOnCheckedChangeListener
            }

            if (isChecked && !preference.enablePrivate) {
                // 第一次开启弹窗设置密码
                binding.swEnaPrivate.isChecked = false // 先取消
                PopupDialog.showPrivatePasswordSettingDialog(
                    onConfirm = {
                        val encrypted = AESUtil.encrypt(it)
                        preference.privatePassword = encrypted
                        preference.enablePrivate = true
                        binding.swEnaPrivate.isChecked = true
                        binding.swPrivate.isEnabled = true
                    },
                    onCancel = {
                        binding.swEnaPrivate.isChecked = false
                    }
                )
            } else {
                preference.enablePrivate = isChecked
                binding.swPrivate.isEnabled = isChecked
            }
        }

        // 隐藏隐私文件
        binding.swPrivate.isEnabled = preference.enablePrivate
        binding.swPrivate.isChecked = preference.isHidePrivateFile
        binding.swPrivate.setOnCheckedChangeListener { _, isChecked ->
            preference.isHidePrivateFile = isChecked
        }

        if (!PermissionHelper.hasPermission(requireActivity(), Manifest.permission.CAMERA)) {
            preference.enableEyeTrace = false
        }
        // 眼球跟踪（需权限）
        binding.swEyeTrace.isChecked = preference.enableEyeTrace
        binding.swEyeTrace.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                if (!PermissionHelper.hasPermission(
                        requireActivity(),
                        Manifest.permission.CAMERA
                    )
                ) {
                    binding.swEyeTrace.isChecked = false
                    PopupDialog.showCameraPermissionRequestDialog(
                        onConfirm = { requestCameraPermission() },
                        onReject = {}
                    )
                } else {
                    preference.enableEyeTrace = true
                }
            } else {
                preference.enableEyeTrace = false
            }
        }



        binding.btnTestVosk.setOnClickListener {
            val pcmFile = File("/storage/emulated/0/Download/5fa57afddda84a14b0eff1f47dcc96de.pcm")
            val destFile = File("/storage/emulated/0/Download/5fa57afddda84a14b0eff1f47dcc96de.srt")

            lifecycleScope.launch(Dispatchers.IO) {
                VOSK debug preference.voskModelPath!!
                assert(File(preference.voskModelPath!!).exists())

                assert(pcmFile.exists())
                destFile.deleteOnExit()
                destFile.createNewFile()
            }

        }
    }


    private fun setupResetButton() {
        binding.btnReset.setOnClickListener {
            // 清除偏好设置
            preference.isMovieMode = false
            preference.enablePrivate = false
            preference.privatePassword = ""
            preference.isHidePrivateFile = false
            preference.isSkipAnimation = false
            preference.enableAudioMode = false
            preference.enableEyeTrace = false
            preference.keepOtherAudio = false

            // 重置 UI
            binding.swMovieMode.isChecked = false
            binding.swEnaPrivate.isChecked = false
            binding.swPrivate.isChecked = false
            binding.swPrivate.isEnabled = false
            binding.swAnimation.isChecked = false
            binding.swAudio.isChecked = false
            binding.swEyeTrace.isChecked = false
            binding.swBlockMp3.isChecked = false

            Toast.makeText(requireContext(), "设置已重置为默认", Toast.LENGTH_SHORT).show()
        }
    }

    private fun requestCameraPermission() {
        PermissionHelper.requestCameraPermission(requireActivity(), object :
            PermissionHelper.PermissionCallback {
            override fun onGranted() {
                binding.swEyeTrace.isChecked = true
                preference.enableEyeTrace = true
            }

            override fun onDenied() {
                binding.swEyeTrace.isChecked = false
                preference.enableEyeTrace = false
                Toast.makeText(requireContext(), "需要相机权限才能开启此功能", Toast.LENGTH_SHORT)
                    .show()
            }
        })
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PermissionHelper.REQUEST_CODE_CAMERA) {
            PERMISSION debug "Result:${grantResults[0]}"
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                binding.swEyeTrace.isChecked = true
            } else {
                binding.swAnimation.isChecked = false
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCameraPermissionEvent(e: CameraPermissionEvent) {
        suppressToggleCallback = true
        binding.swEyeTrace.isChecked = e.isGranted
        handler.postDelayed({
            suppressToggleCallback = false
        }, 1000L)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }
}
